<!DOCTYPE html>


<html lang="zh_CN">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>Ribbon负载均衡服务调用 |  MyBlog</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="MyBlog" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="SpringCloud-Ribbon负载均衡服务调用"
  class="article article-type-SpringCloud"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Ribbon负载均衡服务调用
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/03/12/Ribbon%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8/" class="article-date">
  <time datetime="2022-03-12T14:28:20.000Z" itemprop="datePublished">2022-03-12</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/SpringCloud/">SpringCloud</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.7k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">6 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>[TOC]</p>
<h1 id="八、Ribbon负载均衡服务调用"><a href="#八、Ribbon负载均衡服务调用" class="headerlink" title="八、Ribbon负载均衡服务调用"></a>八、Ribbon负载均衡服务调用</h1><h2 id="8-1-概述"><a href="#8-1-概述" class="headerlink" title="8.1.概述"></a>8.1.概述</h2><h3 id="8-1-1-Ribbon是什么"><a href="#8-1-1-Ribbon是什么" class="headerlink" title="8.1.1.Ribbon是什么"></a>8.1.1.Ribbon是什么</h3><p>Spring Cloud Ribbon是基于Netflix Ribbon实现的一套<font color='red'>客户端       负载均衡的工具</font>。</p>
<p>简单的说，Ribbon是Netflix发布的开源项目，主要功能是提供<font color='red'>客户端的软件负载均衡算法和服务调用</font>。Ribbon客户端组件提供一系列完善的配置项如连接超时，重试等。简单的说，就是在配置文件中列出Load Balancer（简称LB）后面所有的机器，Ribbon会自动的帮助你基于某种规则（如简单轮询，随机连接等）去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。</p>
<h3 id="8-1-2-官网资料"><a href="#8-1-2-官网资料" class="headerlink" title="8.1.2.官网资料"></a>8.1.2.官网资料</h3><p><a target="_blank" rel="noopener" href="https://github.com/Netflix/ribbon/wiki/Getting-Started">https://github.com/Netflix/ribbon/wiki/Getting-Started</a></p>
<p>Ribbon目前也进入维护模式</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203011007419.png" alt="image-20220301100748621"></p>
<p>未来替换方案</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203011008239.png" alt="image-20220301100857851"></p>
<h3 id="8-1-3-Ribbon的用处"><a href="#8-1-3-Ribbon的用处" class="headerlink" title="8.1.3.Ribbon的用处"></a>8.1.3.Ribbon的用处</h3><h4 id="1-LB（负载均衡）"><a href="#1-LB（负载均衡）" class="headerlink" title="1.LB（负载均衡）"></a>1.LB（负载均衡）</h4><blockquote>
<p>LB负载均衡(Load Balance)是什么</p>
</blockquote>
<p>简单的说就是将用户的请求平摊的分配到多个服务上，从而达到系统的HA（高可用）。<br>常见的负载均衡有软件Nginx，LVS，硬件 F5等。</p>
<blockquote>
<p>Ribbon本地负载均衡客户端 VS Nginx服务端负载均衡区别</p>
</blockquote>
<p> <strong>Nginx是服务器负载均衡</strong>，客户端所有请求都会交给nginx，然后由nginx实现转发请求。即负载均衡是由服务端实现的。</p>
<p> <strong>Ribbon本地负载均衡</strong>，在调用微服务接口时候，会在注册中心上获取注册信息服务列表之后缓存到JVM本地，从而在本地实现RPC远程服务调用技术。</p>
<h5 id="（1）集中式LB"><a href="#（1）集中式LB" class="headerlink" title="（1）集中式LB"></a>（1）集中式LB</h5><p>即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件，如F5, 也可以是软件，如<strong>nginx</strong>), 由该设施负责把访问请求通过某种策略转发至服务的提供方</p>
<h5 id="（2）进程内LB"><a href="#（2）进程内LB" class="headerlink" title="（2）进程内LB"></a>（2）进程内LB</h5><p>将LB逻辑集成到消费方，消费方从服务注册中心获知有哪些地址可用，然后自己再从这些地址中选择出一个合适的服务器。</p>
<p><strong>Ribbon就属于进程内LB</strong>，它只是一个类库，<strong>集成于消费方进程</strong>，消费方通过它来获取到服务提供方的地址。</p>
<h4 id="2-可轮询访问"><a href="#2-可轮询访问" class="headerlink" title="2.可轮询访问"></a>2.可轮询访问</h4><h2 id="8-2-Ribbon负载均衡演示"><a href="#8-2-Ribbon负载均衡演示" class="headerlink" title="8.2.Ribbon负载均衡演示"></a>8.2.Ribbon负载均衡演示</h2><h3 id="8-2-1-架构说明"><a href="#8-2-1-架构说明" class="headerlink" title="8.2.1.架构说明"></a>8.2.1.架构说明</h3><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203011217327.png" alt="image-20220301114209805"></p>
<p><strong>总结</strong></p>
<p>Ribbon其实就是一个软负载均衡的客户端软件，他可以和其他所需请求的客户端结合使用，和eureka结合只是其中的一个实例</p>
<h3 id="8-2-2-修改pom文件"><a href="#8-2-2-修改pom文件" class="headerlink" title="8.2.2.修改pom文件"></a>8.2.2.修改pom文件</h3><p>之前写样例时候没有引入spring-cloud-starter-ribbon也可以使用ribbon,</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-ribbon<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>猜测spring-cloud-starter-netflix-eureka-client起步依赖帮我们导入了spring-cloud-starter-ribbon引用</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012058358.png" alt="image-20220301205801483"></p>
<h3 id="8-2-3-RestTemplate的使用"><a href="#8-2-3-RestTemplate的使用" class="headerlink" title="8.2.3.RestTemplate的使用"></a>8.2.3.RestTemplate的使用</h3><h4 id="1-官网"><a href="#1-官网" class="headerlink" title="1.官网"></a>1.官网</h4><p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html">https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html</a></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012111325.png" alt="image-20220301211142055"></p>
<h4 id="2-getForObject方法-getForEntity方法"><a href="#2-getForObject方法-getForEntity方法" class="headerlink" title="2.getForObject方法/getForEntity方法"></a>2.getForObject方法/getForEntity方法</h4><blockquote>
<p>getForObject</p>
</blockquote>
<p>返回对象为响应体中数据转化成对象，基本可以理解为json</p>
<blockquote>
<p>getForEntity</p>
</blockquote>
<p>返回对象为ResponseEntity对象，包含了响应中的一些重要信息，比如响应头、响应状态码、响应体等</p>
<h2 id="8-3-Ribbon核心组件IRule"><a href="#8-3-Ribbon核心组件IRule" class="headerlink" title="8.3.Ribbon核心组件IRule"></a>8.3.Ribbon核心组件IRule</h2><h3 id="8-3-1-IRule：根据特定算法中从服务列表中选取一个要访问的服务"><a href="#8-3-1-IRule：根据特定算法中从服务列表中选取一个要访问的服务" class="headerlink" title="8.3.1. IRule：根据特定算法中从服务列表中选取一个要访问的服务"></a>8.3.1. IRule：根据特定算法中从服务列表中选取一个要访问的服务</h3><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012143933.png" alt="image-20220301214323974"></p>
<h4 id="1-com-netflix-loadbalancer-RoundRobinRule"><a href="#1-com-netflix-loadbalancer-RoundRobinRule" class="headerlink" title="1.com.netflix.loadbalancer.RoundRobinRule"></a>1.com.netflix.loadbalancer.RoundRobinRule</h4><p>轮询</p>
<h4 id="2-com-netflix-loadbalancer-RandomRule"><a href="#2-com-netflix-loadbalancer-RandomRule" class="headerlink" title="2.com.netflix.loadbalancer.RandomRule"></a>2.com.netflix.loadbalancer.RandomRule</h4><p>随机</p>
<h4 id="3-com-netflix-loadbalancer-RetryRule"><a href="#3-com-netflix-loadbalancer-RetryRule" class="headerlink" title="3.com.netflix.loadbalancer.RetryRule"></a>3.com.netflix.loadbalancer.RetryRule</h4><p>先按照RoundRobinRule的策略获取服务，如果获取服务失败则在指定时间内会进行<strong>重试</strong>，获取可用的服务</p>
<h4 id="4-WeightedResponseTimeRule"><a href="#4-WeightedResponseTimeRule" class="headerlink" title="4.WeightedResponseTimeRule"></a>4.WeightedResponseTimeRule</h4><p>对RoundRobinRule的扩展，响应速度越快的实例选择权重越大，越容易被选择</p>
<h4 id="5-BestAvailableRule"><a href="#5-BestAvailableRule" class="headerlink" title="5.BestAvailableRule"></a>5.BestAvailableRule</h4><p>先过滤掉由于多次访问故障而处于断路器跳闸状态的服务，然后选择一个并发量最小的服务</p>
<h4 id="6-AvailabilityFilteringRule"><a href="#6-AvailabilityFilteringRule" class="headerlink" title="6.AvailabilityFilteringRule"></a>6.AvailabilityFilteringRule</h4><p>先过滤故障实例，再进行轮询选择</p>
<h4 id="7-ZoneAvoidanceRule"><a href="#7-ZoneAvoidanceRule" class="headerlink" title="7.ZoneAvoidanceRule"></a>7.ZoneAvoidanceRule</h4><p>默认规则，复合判断server所在区域的性能和server的可用性选择服务器</p>
<h3 id="8-3-2-替换负载均衡的规则"><a href="#8-3-2-替换负载均衡的规则" class="headerlink" title="8.3.2.替换负载均衡的规则"></a>8.3.2.替换负载均衡的规则</h3><h4 id="1-配置需注意的细节"><a href="#1-配置需注意的细节" class="headerlink" title="1.配置需注意的细节"></a>1.配置需注意的细节</h4><p><font color='blue'>官方文档明确给出了警告：</font><br>这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下，否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享，<strong>达不到特殊化定制</strong>的目的了。</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012153594.png" alt="image-20220301215355196"></p>
<h4 id="2-新建package"><a href="#2-新建package" class="headerlink" title="2.新建package"></a>2.新建package</h4><p>com.myrule</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012200608.png" alt="image-20220301220031440"></p>
<h4 id="3-在新建的包下创建MySelfRule类"><a href="#3-在新建的包下创建MySelfRule类" class="headerlink" title="3.在新建的包下创建MySelfRule类"></a>3.在新建的包下创建MySelfRule类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MySelfRule</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> IRule <span class="title">iRule</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> RandomRule();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4-在启动类上标记-RibbonClient注解"><a href="#4-在启动类上标记-RibbonClient注解" class="headerlink" title="4.在启动类上标记@RibbonClient注解"></a>4.在启动类上标记@RibbonClient注解</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RibbonClient(name = &quot;CLOUD-PAYMENT-SERVICE&quot;,configuration=MySelfRule.class)</span></span><br></pre></td></tr></table></figure>

<h4 id="5-测试"><a href="#5-测试" class="headerlink" title="5.测试"></a>5.测试</h4><h2 id="8-4-Ribbon负载均衡算法"><a href="#8-4-Ribbon负载均衡算法" class="headerlink" title="8.4.Ribbon负载均衡算法"></a>8.4.Ribbon负载均衡算法</h2><h3 id="8-4-1-原理"><a href="#8-4-1-原理" class="headerlink" title="8.4.1.原理"></a>8.4.1.原理</h3><p><font color='red'><strong>负载均衡算法：rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ，每次服务重启动后rest接口计数从1开始。</strong></font></p>
<p>List<ServiceInstance> instances = discoveryClient.getInstances(“CLOUD-PAYMENT-SERVICE”);</p>
<p>如：   List [0] instances = 127.0.0.1:8002<br>　　　List [1] instances = 127.0.0.1:8001</p>
<p>8001+ 8002 组合成为集群，它们共计2台机器，集群总数为2， 按照轮询算法原理：</p>
<p>当总请求数为1时： 1 % 2 =1 对应下标位置为1 ，则获得服务地址为127.0.0.1:8001<br>当总请求数位2时： 2 % 2 =0 对应下标位置为0 ，则获得服务地址为127.0.0.1:8002<br>当总请求数位3时： 3 % 2 =1 对应下标位置为1 ，则获得服务地址为127.0.0.1:8001<br>当总请求数位4时： 4 % 2 =0 对应下标位置为0 ，则获得服务地址为127.0.0.1:8002<br>如此类推……</p>
<h3 id="8-4-2-RoundRobinRule源码"><a href="#8-4-2-RoundRobinRule源码" class="headerlink" title="8.4.2.RoundRobinRule源码"></a>8.4.2.RoundRobinRule源码</h3><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012258130.png" alt="image-20220301225840027"></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012300177.png" alt="image-20220301230003123"></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203012300320.png" alt="image-20220301230039243"></p>
<h3 id="8-4-3-自定义负载均衡算法"><a href="#8-4-3-自定义负载均衡算法" class="headerlink" title="8.4.3.自定义负载均衡算法"></a>8.4.3.自定义负载均衡算法</h3><h4 id="1-7001-7002集群启动"><a href="#1-7001-7002集群启动" class="headerlink" title="1. 7001/7002集群启动"></a>1. 7001/7002集群启动</h4><h4 id="2-8001-8002微服务改造controller"><a href="#2-8001-8002微服务改造controller" class="headerlink" title="2. 8001/8002微服务改造controller"></a>2. 8001/8002微服务改造controller</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping(value = &quot;/payment/lb&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getPaymentLB</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> serverPort;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-8080端口微服务改造"><a href="#3-8080端口微服务改造" class="headerlink" title="3. 8080端口微服务改造"></a>3. 8080端口微服务改造</h4><h5 id="（1）ApplicationContextConfig去掉-LoadBalanced注解"><a href="#（1）ApplicationContextConfig去掉-LoadBalanced注解" class="headerlink" title="（1）ApplicationContextConfig去掉@LoadBalanced注解"></a>（1）ApplicationContextConfig去掉@LoadBalanced注解</h5><h5 id="（2）自定义类实现LoadBalancewe接口"><a href="#（2）自定义类实现LoadBalancewe接口" class="headerlink" title="（2）自定义类实现LoadBalancewe接口"></a>（2）自定义类实现LoadBalancewe接口</h5><p>接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">LoadBalancer</span> </span>&#123;</span><br><span class="line">    <span class="function">ServiceInstance <span class="title">instances</span><span class="params">(List&lt;ServiceInstance&gt; serviceInstances)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyLB</span> <span class="keyword">implements</span> <span class="title">LoadBalancer</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> AtomicInteger atomicInteger = <span class="keyword">new</span> AtomicInteger(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">getAndIncrement</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">int</span> current;</span><br><span class="line">        <span class="keyword">int</span> next;</span><br><span class="line">        <span class="keyword">do</span>&#123;</span><br><span class="line">            current = <span class="keyword">this</span>.atomicInteger.get();</span><br><span class="line">            next = current &gt;= Integer.MAX_VALUE ? <span class="number">0</span>:current+<span class="number">1</span>;</span><br><span class="line">            <span class="comment">//如果期望值没变就继续执行，如果变了就跳出循环，期望值是current</span></span><br><span class="line">        &#125;<span class="keyword">while</span>(!<span class="keyword">this</span>.atomicInteger.compareAndSet(current,next));</span><br><span class="line">        System.out.println(<span class="string">&quot;******第几次访问，次数next:&quot;</span>+next);</span><br><span class="line">        <span class="keyword">return</span> next;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ServiceInstance <span class="title">instances</span><span class="params">(List&lt;ServiceInstance&gt; serviceInstances)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//获得下标索引</span></span><br><span class="line">        <span class="keyword">int</span> index = getAndIncrement() % serviceInstances.size();</span><br><span class="line">        <span class="keyword">return</span> serviceInstances.get(index);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="（3）OrderController"><a href="#（3）OrderController" class="headerlink" title="（3）OrderController"></a>（3）OrderController</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Resource</span></span><br><span class="line"><span class="keyword">private</span> LoadBalancer loadBalancer;</span><br><span class="line"><span class="meta">@Resource</span></span><br><span class="line"><span class="keyword">private</span> DiscoveryClient discoveryClient;</span><br><span class="line"><span class="meta">@GetMapping(&quot;/consumer/payment/lb&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">serverPort</span><span class="params">()</span></span>&#123;</span><br><span class="line">    List&lt;ServiceInstance&gt; instances = discoveryClient.getInstances(<span class="string">&quot;CLOUD-PAYMENT-SERVICE&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(instances == <span class="keyword">null</span> || instances.size()&lt;=<span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    ServiceInstance serviceInstance = loadBalancer.instances(instances);</span><br><span class="line">    URI uri = serviceInstance.getUri();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(uri+<span class="string">&quot;/payment/lb&quot;</span>,String.class);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="（4）测试"><a href="#（4）测试" class="headerlink" title="（4）测试"></a>（4）测试</h5> 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2022/03/12/Ribbon%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/SpringCloud/" rel="tag">SpringCloud</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/03/12/OpenFeign%E6%9C%8D%E5%8A%A1%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            OpenFeign服务接口调用
          
        </div>
      </a>
    
    
      <a href="/2022/03/12/SpringCloud%20Alibaba%20Nocos%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E5%92%8C%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">SpringCloud Alibaba Nocos服务注册和配置中心</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> Yuan
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="MyBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->
 
<script src="/js/clickLove.js"></script>
 
<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=22707008&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
    

  </div>
</body>

</html>